package qeug.shsh.bpm.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.mail.imap.protocol.BODY;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import okhttp3.*;
import org.springframework.util.Base64Utils;
import qeug.shsh.bpm.annotation.ThridSrevice;
import qeug.shsh.bpm.domain.*;
import qeug.shsh.bpm.service.SAPService;
import qeug.shsh.helper.FacadeHelper;

import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.bpm.service.impl
 * @className: SAPServicelmpl
 * @author: xuhaihui
 * @description: 费控凭证传SAP
 * @date: 2024/3/13
 * @version: 1.0
 */

@ThridSrevice("SAPServicelmpl")
public class SAPServicelmpl implements SAPService {

    @Override
    public String voucher(DynamicObject gl_voucher) throws ServiceException, RemoteException, MalformedURLException {

        String sap_url = System.getProperty("sapadd.url");
        String basicAuthUserName = System.getProperty("sap.user");
        String basicAuthPassword = System.getProperty("sap.password");
//        String basicAuthUserName = "ccsuser";
//        String basicAuthPassword = "ccs2sappoqas";

        HashMap<String, Object> log = new HashMap<>();
        log.put("operationModule", "凭证推送");
        log.put("url", sap_url);
        log.put("user", basicAuthUserName);
        log.put("mode", "POST");
        log.put("action", "");
        log.put("opdate", new Date());
        SapVoucherInfo sapVoucherInfo = new SapVoucherInfo();
        ArrayList<SapEntry> sapentrys = new ArrayList<>();
//        DynamicObject GJAHR = gl_voucher.getDynamicObject("period");//期间
//        String GJAHRS = GJAHR.getString("periodyear");
        DynamicObject BUKRS = gl_voucher.getDynamicObject("org");//核算组织
//        DynamicObject company = gl_voucher.getDynamicObject("company");//公司
//        String BUKRS = company.getString("number");
        String BUKRSNUM = BUKRS.getString("number");
        String BLART = gl_voucher.getString("qeug_vouchertype");//凭证类型
        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
        Date BLDAT = gl_voucher.getDate("bizdate");//业务日期(凭证日期)
        String BLDATTDate = targetFormat.format(BLDAT);
        Date BUDAT = gl_voucher.getDate("bookeddate");//记账日期
        String BUDATDate = targetFormat.format(BUDAT);
        String test = new SimpleDateFormat("yyyy").format(BUDAT);//方法二   一般为.format(new Date())
        String XBLNR = gl_voucher.getString("billno");//凭证号
        DynamicObject WAERS = gl_voucher.getDynamicObject("localcur");//组织本位币
        String WAERSNAME = WAERS.getString("number");
        if ("CNY".equals(WAERSNAME)) {
            sapVoucherInfo.setWAERS("RMB");
        } else {
            sapVoucherInfo.setWAERS(WAERSNAME);
        }
        String XREF1_HD = gl_voucher.getString("qeug_nbcgjz");//凭证  id
        String BKTXT = gl_voucher.getString("vdescription");//时序簿摘要
        DynamicObject USNAM = gl_voucher.getDynamicObject("creator");//创建人工号+（CCS）
        String USNAMNUM = USNAM.getString("number");
        DynamicObject sourceBillType = gl_voucher.getDynamicObject("sourcebilltype");
        String source = sourceBillType.getString("id");
        String ZUONRID = gl_voucher.getString("sourcebill");//源单id
        long fundPlAnEntryLong = Long.parseLong(ZUONRID);
        QFilter[] qFilters = new QFilter[]{
                new QFilter("id", QCP.equals, fundPlAnEntryLong)
        };
        String billno = "";
        DynamicObject sourcebill = BusinessDataServiceHelper.loadSingle(source, "billno", qFilters);
        if (sourcebill != null) {
            billno = sourcebill.getString("billno");
        }
        boolean isbuild = false;
        QFilter[] qFilte = new QFilter[]{new QFilter("voucherid", "=", gl_voucher.getLong("id"))};
        DynamicObject[] daptracker = BusinessDataServiceHelper.load("ai_daptracker","billtype,sourcebillid,voucherid", qFilte);
        sapVoucherInfo.setBELNR("");//会计凭证号码(费控系统传空
        sapVoucherInfo.setGJAHR(test);
//        sapVoucherInfo.setBUKRS("5800");//核算组织
        sapVoucherInfo.setBUKRS(BUKRSNUM);//核算组织
        sapVoucherInfo.setBLART(BLART);
        sapVoucherInfo.setBLDAT(BLDATTDate);
        sapVoucherInfo.setBUDAT(BUDATDate);
//        sapVoucherInfo.setBLDAT("20250131");
//        sapVoucherInfo.setBUDAT("20250131");
        sapVoucherInfo.setXBLNR(XBLNR);
        sapVoucherInfo.setXREF1_HD(XREF1_HD);
        sapVoucherInfo.setBKTXT(BKTXT);
        sapVoucherInfo.setUSNAM(USNAMNUM + "CCS");

        DynamicObjectCollection entriesCollection = gl_voucher.getDynamicObjectCollection("entries");//分录
        for (DynamicObject entriesEntry : entriesCollection) {
            SapEntry sapEntry = new SapEntry();
            String BUZEI = entriesEntry.getString("seq");//分录行号
            BigDecimal debitlocal = entriesEntry.getBigDecimal("debitlocal");//借方金额
            //借方金额内有值代表为借方，否则为贷方：借方传S，贷方传H
            if (debitlocal != null && debitlocal.doubleValue() != 0) {
                BigDecimal WRBTR = entriesEntry.getBigDecimal("debitori");//原币借方
                sapEntry.setWRBTR(WRBTR);
                sapEntry.setSHKZG("S");
            } else {
                BigDecimal WRBTR = entriesEntry.getBigDecimal("creditori");//原币贷方
                sapEntry.setWRBTR(WRBTR);
                sapEntry.setSHKZG("H");
            }
            DynamicObject HKONT = entriesEntry.getDynamicObject("account");//科目
            if (HKONT!=null){
                QFilter[] q1 = new QFilter[]{new QFilter("number", "=", HKONT.getString("number"))};
                DynamicObject account = BusinessDataServiceHelper.loadSingle("bd_accountview", q1);
                String HKONTSNUM = account.getString("qeug_sapnumber");
                DynamicObjectCollection checkItemCollection = HKONT.getDynamicObjectCollection("checkitementry");//核算维度分录
                if (checkItemCollection != null) {
                    //核算维度分录存在值，进入循环
                    for (DynamicObject checkItemEntry : checkItemCollection) {
                        DynamicObject assTactItem = checkItemEntry.getDynamicObject("asstactitem");
                        String assTactItemNumber = assTactItem.getString("number");//核算维度编码
                        DynamicObject assgrp = entriesEntry.getDynamicObject("assgrp");//核算维度（弹性域

                        String KUNNR = "";//客户
                        String LIFNR = "";//供应商
                        String KOSTL = "";//成本中心 部门
                        String PROJK = "";//wbs
                        String PRCTR = "";//利润中心
                        String AUFNR = "";//订单编号
                        String RSTGR = "";//付款原因代码
                        String MNDID = "";//银行账户
                        String ZUONR = "";//票据号
                        String UMSKZ = "";//特殊总账标识

                        if (null != assgrp) {
                            QFilter filter = new QFilter("hg.id", QCP.equals, assgrp.getPkValue());
                            DynamicObjectCollection gl_assist_bd = QueryServiceHelper.query("gl_assist_bd", "hg.id,asstype,assval", new QFilter[]{filter});
                            for (int j = 0; j < gl_assist_bd.size(); j++) {
                                DynamicObject gl_assist_bdObject = gl_assist_bd.get(j);
                                Long hgId = gl_assist_bdObject.getLong("hg.id");
                                Long assval = gl_assist_bdObject.getLong("assval");//维度值
                                String asstype = gl_assist_bdObject.getString("asstype");
                                switch (asstype) {
                                    case "f0001":
                                        //客户
                                        DynamicObject dynamicObject = QueryServiceHelper.queryOne("bd_customer", "id,name,number,shkd_sap_number", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        KUNNR = dynamicObject.getString("number");
                                        sapEntry.setLIFNR(KUNNR);
                                        break;
                                    case "f000003":
                                        //银行账户
                                        dynamicObject = QueryServiceHelper.queryOne("am_accountbank", "id,name,number,bankaccountnumber", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        MNDID = dynamicObject.getString("bankaccountnumber");
                                        sapEntry.setMNDID(MNDID);
                                        break;
                                    case "f000005":
                                        //供应商
                                        dynamicObject = QueryServiceHelper.queryOne("bd_supplier", "id,name,number", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        LIFNR = dynamicObject.getString("number");
                                        sapEntry.setLIFNR(LIFNR);
                                        break;
                                    case "f000011":
                                        //部门
                                        dynamicObject = QueryServiceHelper.queryOne("bos_costcenter", "id,name,number", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        KOSTL = dynamicObject.getString("number");
                                        sapEntry.setKOSTL(KOSTL);//成本中心编码
//                                    sapEntry.setKOSTL("8580010008");//成本中心编码
                                        break;
                                    case "f000012":
                                        //wbs
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number,qeug_wbsfactor", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        PROJK = dynamicObject.getString("qeug_wbsfactor");
                                        sapEntry.setPROJK(PROJK);//工作分解结构元素;WBS元素(若费控有填写则传，不传则传空
                                        break;

                                    case "f000013":
                                        //chengben中心
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        PRCTR = dynamicObject.getString("number");
                                        sapEntry.setPRCTR(PRCTR);//利润中心(若费控有填写则传，不传则传空
                                        break;
                                    case "f000015":
                                        //付款原因代码
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        RSTGR = dynamicObject.getString("number");
                                        sapEntry.setRSTGR(RSTGR);//付款原因代码(若费控有填写则传，不传则传空
                                        break;
                                    case "f000017":
                                        //新内部订单号 福利
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number,qeug_oredernum", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        AUFNR = dynamicObject.getString("qeug_oredernum");
                                        sapEntry.setAUFNR(AUFNR);//内部订单号
                                        break;
                                    case "f000022":
                                        //新内部订单号  研发
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number,qeug_oredernum", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        AUFNR = dynamicObject.getString("qeug_oredernum");
                                        sapEntry.setAUFNR(AUFNR);//内部订单号、
                                        break;
                                    case "f000020":
                                        //特殊总账标识
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        UMSKZ = dynamicObject.getString("number");
                                        sapEntry.setUMSKZ(UMSKZ);//特殊总账标识
                                        break;
                                    case "f000019":
                                        //wbs
                                        dynamicObject = QueryServiceHelper.queryOne("bos_assistantdata_detail", "id,name,number,qeug_wbsfactor", new QFilter[]{new QFilter("id", QCP.equals, assval)});
                                        PROJK = dynamicObject.getString("qeug_wbsfactor");
                                        sapEntry.setPROJK(PROJK);//工作分解结构元素;WBS元素(若费控有填写则传，不传则传空
                                        break;
                                    default:
                                        break;
                                }
                            }
                            int startIndex = assgrp.toString().indexOf("{");
                            int endIndex = assgrp.toString().lastIndexOf("}");
                            String jsonStr = assgrp.toString().substring(startIndex, endIndex + 1);
                            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//                            AUFNR = jsonObject.getString("f000021");
                            ZUONR = jsonObject.getString("f000016");
//                            sapEntry.setAUFNR(AUFNR);//内部订单号 研发文本
                            sapEntry.setZUONR(ZUONR);//票据号
                        }
                    }
                }
                sapEntry.setHKONT(HKONTSNUM);//科目编码w
            }else {
                return "推送至SAP失败，异常原因: 分录中科目不能为空！";
            }
            String SGTXT = entriesEntry.getString("edescription");//摘要
            sapEntry.setBUZEI(BUZEI);
//            sapEntry.setHKONT("2221010102");//科目编码w
//            sapEntry.setKOSTL("8580010006");//成本中心编码
            sapEntry.setVALUT(BLDATTDate);
//            sapEntry.setVALUT("20250131");
//            if (daptracker!=null){
//                DynamicObject dynamicObject = daptracker[0];
//                DynamicObject billtype = dynamicObject.getDynamicObject("billtype");
//                String billnumber = billtype.getString("number");
//                if(billnumber.equals("er_tripreimbursebill") || billnumber.equals("er_dailyreimbursebill")){
//                    String accountnumber= account.getString("number");
//                    if(accountnumber.substring(0,2).equals("66")){
//                        sapEntry.setZUONR("123456789");
//                    } else if (accountnumber.substring(0,4).equals("1002")) {
//                        sapEntry.setZUONR(BLDATTDate);
//                    }
//                }else {
//                    long sourcebillid = dynamicObject.getLong("sourcebillid");
//                    QFilter[] qf1 = new QFilter[]{new QFilter("id", "=", sourcebillid)};
//                    DynamicObject bill = BusinessDataServiceHelper.loadSingle(billnumber, qf1);
//                    sapEntry.setZUONR(bill.getString("billno"));
//                }
//            }
            sapEntry.setSGTXT(SGTXT);
            sapEntry.setZFBDT("");//票据到票日期(若费控有填写则传，不传则传空
            sapEntry.setZTERM("");//收付条件代码;付款条件(若费控有填写则传，不传则传空
//            sapEntry.setUMSKZ(entriesEntry.getString("queg_specialsign"));//特殊总账标识
            sapentrys.add(sapEntry);
        }

        SapInfo bpmInfo = new SapInfo();
        bpmInfo.setIT_BSEG(sapentrys);
        bpmInfo.setIW_BKPF(sapVoucherInfo);
        String json = JSONObject.toJSONString(bpmInfo);

        String basic = basicAuthUserName + ":" + basicAuthPassword;
        String encoding = Base64Utils.encodeToString(basic.getBytes(StandardCharsets.UTF_8));
        String send_standard = HttpRequest.post(sap_url)
                .header("Authorization", "Basic " + encoding)
                .body(json)
                .execute().body();
        log.put("mainstring", json);
        log.put("responsebody", send_standard);

        JSONObject jsonObject = JSONObject.parseObject(send_standard);
        Object ztreturn = jsonObject.get("ZTRETURN");
        List<String> errors = new ArrayList<>();
        OperateOption option = OperateOption.create();
        if (ztreturn instanceof JSONArray) {
            JSONArray ztreturnArray = (JSONArray) ztreturn;
            for (int i = 0; i < ztreturnArray.size(); i++) {
                JSONObject ztReturnObject = ztreturnArray.getJSONObject(i);
                String msgTyp = ztReturnObject.getString("MSGTYP");
                if ("S".equals(msgTyp)) {
                    log.put("pdesc", "成功");
                    FacadeHelper.apiLog(log);
                    String AWKEY = jsonObject.getString("AWKEY");
                    gl_voucher.set("qeug_objectkey", AWKEY);
                    OperationServiceHelper.executeOperate("save", "gl_voucher", new DynamicObject[]{gl_voucher}, option);
                    return "凭证推送成功！";
                } else {
                    String error = ztReturnObject.getString("MESSAGE");
                    errors.add(error);
                    gl_voucher.set("qeug_errormsg", error);
                }
            }
            if (!errors.isEmpty()) {
                Object[] saveOperationResult = SaveServiceHelper.save(new DynamicObject[]{gl_voucher});//项目实体
                log.put("pdesc", "失败");
                FacadeHelper.apiLog(log);
                String errorMessage = String.join("; ", errors);
                return "推送至SAP失败，异常原因: " + errorMessage;
            }

        } else if (ztreturn instanceof JSONObject) {
            JSONObject ztReturnObject = (JSONObject) ztreturn;
            String msgTyp = ztReturnObject.getString("MSGTYP");
            if ("S".equals(msgTyp)) {
                log.put("pdesc", "成功");
                FacadeHelper.apiLog(log);
                String AWKEY = jsonObject.getString("AWKEY");
                gl_voucher.set("qeug_objectkey", AWKEY);
                Object[] saveOperationResult = SaveServiceHelper.save(new DynamicObject[]{gl_voucher});//项目实体？
                return "凭证推送成功！";
            } else {
                String error = ztReturnObject.getString("MESSAGE");
                errors.add(error);
                gl_voucher.set("qeug_errormsg", error);
            }
            if (!errors.isEmpty()) {
                Object[] saveOperationResult = SaveServiceHelper.save(new DynamicObject[]{gl_voucher});//项目实体
                log.put("pdesc", "失败");
                FacadeHelper.apiLog(log);
                String errorMessage = String.join("; ", errors);
//                throw new RuntimeException("推送至SAP失败，异常原因: " + errorMessage);
                return "推送至SAP失败，异常原因: " + errorMessage;
            }
        }
        return "调用SAP推送接口Auth认证失败！";
    }

    @Override
    public String backVoucher(DynamicObject gl_voucher) throws ServiceException, RemoteException, MalformedURLException {
        String qeug_objectkey = gl_voucher.getString("qeug_objectkey");
//        String qeug_objectkey = ("150000001058002025");
        String result = "";

        if (!qeug_objectkey.isEmpty()) {

            // 第一段：去除整个字符串的后八位   凭证号
            String BELNR = qeug_objectkey.substring(0, qeug_objectkey.length() - 8);

            // 第二段：取整个字符串的倒数第四位至倒数第八位    公司代码
            String BUKRS = qeug_objectkey.substring(qeug_objectkey.length() - 8, qeug_objectkey.length() - 4);

            // 第三段：取最后四位    年度
            String GJAHR = qeug_objectkey.substring(qeug_objectkey.length() - 4);

            JSONObject body = new JSONObject();
            body.put("BELNR", BELNR);
            body.put("BUKRS", BUKRS);
            body.put("GJAHR", GJAHR);
            body.put("STGRD", "03");
            body.put("BUDAT", "");
            String url = System.getProperty("sapback.url");
            String basicAuthUserName = "ccsuser";
//            String basicAuthPassword = "ccs2sappodev";
            String sapapi = FacadeHelper.getSAPAPI(body.toJSONString(), url);
            //{"RESULT":{"BELNR":1500000005,"BUKRS":5800,"GJAHR":2025},"MSGTY":"S","MESSAGE":"冲销成功"}
            JSONObject jsonObject = JSONObject.parseObject(sapapi);
            String msgty = jsonObject.getString("MSGTY");
            HashMap<String, Object> log = new HashMap<>();
            log.put("operationModule", "凭证冲销");
            log.put("url", url);
            log.put("user", basicAuthUserName);
            log.put("mode", "POST");
            log.put("action", "");
            log.put("opdate", new Date());
            log.put("mainstring", body.toJSONString());
            log.put("responsebody", sapapi);
            if (msgty.equals("S")) {//成功
                log.put("pdesc", "成功");
                JSONObject result1 = jsonObject.getJSONObject("RESULT");
                String belnr = result1.getString("BELNR");
                String bukrs = result1.getString("BUKRS");
                String gjahr = result1.getString("GJAHR");
                gl_voucher.set("qeug_cxvoucher", belnr + bukrs + gjahr);
                Object[] saveOperationResult = SaveServiceHelper.save(new DynamicObject[]{gl_voucher});//项目实体
                result = msgty;
            } else {//失败
                log.put("pdesc", "失败");
                result = jsonObject.getString("MESSAGE");
            }
            FacadeHelper.apiLog(log);
        }
        return result;
    }

    @Override
    public String getBankInfo(String body) {
        try {
            String BODY = "";
            if (body == null) {
                JSONObject jsonbody = new JSONObject();
//            jsonbody.put("IM_BUKRS","5800");
                BODY = jsonbody.toJSONString();
            } else {
                JSONObject jsonbody = JSONObject.parseObject(body);
                BODY = jsonbody.toJSONString();
            }
            String url = System.getProperty("sapbank.url");
//            url = "http://10.10.101.132:50000/RESTAdapter/CCS2S4/GETBANKINFO";
            String bankInfo = FacadeHelper.getSAPAPI(BODY, url);
            JSONObject jsonObject = JSONObject.parseObject(bankInfo);
            JSONArray ex_zzbank = jsonObject.getJSONArray("EX_ZZBANK");
            HashMap<String, Object> log = new HashMap<>();
            String message = null;
            JSONObject root = new JSONObject(new LinkedHashMap<>());
            JSONArray dataArray = new JSONArray();
            for (int i = 0; i < ex_zzbank.size(); i++) {
                JSONObject dataItem = new JSONObject(true);
                JSONObject bank = ex_zzbank.getJSONObject(i);
                String bukrs = bank.getString("BUKRS");//公司代码
                String hbkid = bank.getString("HBKID");//开户行简短代码
                String hktid = bank.getString("HKTID");//账户细目的代码
                String bnkn2 = bank.getString("BNKN2");//f银行账号
                if (bnkn2 == null || bnkn2.isEmpty()) {
                    continue;
                }
                String bankl = bank.getString("BANKL");//银行联号
                String waers = bank.getString("WAERS");//币别
                String hkont = bank.getString("HKONT");//会计科目
                DynamicObject bukrsInfo = FacadeHelper.getDynamicObject("bos_org", "number", bukrs);
//                dataItem.put("useorg_number", bukrs);//申请公司
                dataItem.put("company_number", bukrs);//申请公司
                dataItem.put("openorg_number", bukrs);//开户公司18255112908
                dataItem.put("createorg_number", bukrs);//
//            dataItem.put("org",bukrs);//组织
                dataItem.put("finorgtype", "0");//金融机构类别

                DynamicObject finorginfo = FacadeHelper.getDynamicObject("bd_finorginfo", "number", bankl);
                if (finorginfo != null) {
                    dataItem.put("bank_number", finorginfo.getString("number"));//开户行
                } else {
                    DynamicObject banklInfo = changeAccountbank(bankl);
                    if (banklInfo != null) {
                        dataItem.put("bank_number", banklInfo.getString("number"));//开户行
                    } else {
                        continue;
                    }
                }
                dataItem.put("acctname", bukrs + hktid);//账户名称
                dataItem.put("bankaccountnumber", bnkn2);//银行账号
                DynamicObject accountbank = FacadeHelper.getDynamicObject("am_accountbank", "bankaccountnumber", bnkn2);
//                if (accountbank!=null){
//                    dataItem.put("id",accountbank.getLong("id"));
//                }
                dataItem.put("name", bukrsInfo.getString("name") + bnkn2.substring(bnkn2.length() - 4));//账户简称
                String currencyName = "CNY";
                if (waers.equals("RMB")) {
                    currencyName = "CNY";
                }

                dataItem.put("elecpaymenttype", "WT09");//钱包类型
                dataItem.put("elecpaymentlevel", "WL01");//钱包等级
                // 创建currency数组
                JSONArray currencyArray = new JSONArray();
                // 创建currency对象
                JSONObject currencyObject = new JSONObject();
                currencyObject.put("number", "CNY");
                // 将currency对象添加到currency数组
                currencyArray.add(currencyObject);
                // 将currency数组添加到主JSON对象
                dataItem.put("currency", currencyArray);
                dataItem.put("acctstyle", "normal");//账户类型
                dataItem.put("accttype", "in_out");//账户性质
                dataItem.put("acctproperty_number", "01");//账户用途
                dataItem.put("opendate", new Date());//开户日期
//                dataItem.put("createtime", new Date());//开户日期
                dataItem.put("acctstatus", "normal");//账户状态
                dataItem.put("manager_number", "SAPS4001");//账户管理人
                dataItem.put("qeug_hbkid", hbkid);//
                dataItem.put("qeug_hktid", hktid);//
                dataItem.put("defaultcurrency_number", "CNY");//

                QFilter[] q1 = new QFilter[]{new QFilter("qeug_sapnumber", "=", hkont)};
                DynamicObject account = BusinessDataServiceHelper.loadSingle("bd_accountview", q1);
                if (account != null) {
                    dataItem.put("qeug_account_number", account.getString("number"));//会计科目
                }
                dataArray.add(dataItem);
            }
            root.put("data", dataArray);
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body1 = RequestBody.create(mediaType, root.toJSONString());
            Request request = new Request.Builder()
                    .url("http://10.10.102.30:30088/ierp/kapi/v2/qeug/am/am_accountbank/saveaccountbank")//uat
                    .method("POST", body1)
                    .addHeader("access_token", FacadeHelper.getToken())
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            message = response.body().string();
            String basicAuthUserName = "ccsuser";
            log.put("operationModule", "获取银行账户");
            log.put("url", url);
            log.put("user", basicAuthUserName);
            log.put("mode", "POST");
            log.put("action", "");
            log.put("opdate", new Date());
            log.put("mainstring", message);
            log.put("responsebody", bankInfo);
            log.put("operating_mode", message);
            FacadeHelper.apiLog(log);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * 行名行号转换为合作金融机构
     *
     * @param bank 行名行号
     * @return金融机构
     */
    public DynamicObject changeAccountbank(String bank) {
        DynamicObject accountbank = ORM.create().newDynamicObject("bd_finorginfo");
        QFilter[] qFilters = new QFilter[]{new QFilter("number", "=", bank)};
        DynamicObject bebank = BusinessDataServiceHelper.loadSingle("bd_bebank", qFilters);
        if (bebank != null) {
            DynamicObject finorgtype = FacadeHelper.getDynamicObject("bd_finorgtype", "number", "FI-014");
            accountbank.set("finorgtype", finorgtype);//金融机构类别
            accountbank.set("number", bebank.getString("number"));//编码
            accountbank.set("bebank", bebank);//行名行号
            accountbank.set("name", bebank.getString("name"));//名称
            accountbank.set("country", bebank.getDynamicObject("country"));//国家
            DynamicObject bankcgsetting = FacadeHelper.getDynamicObject("bd_bankcgsetting", "number", "BC-9999");
            accountbank.set("bank_cate", bankcgsetting);//银行类别
            accountbank.set("province", bebank.getDynamicObject("province"));//省份
            accountbank.set("city", bebank.getDynamicObject("city"));//城市
            accountbank.set("union_number", bebank.getString("union_number"));//联行号
            OperationResult operationResult = SaveServiceHelper.saveOperate("bd_finorginfo", new DynamicObject[]{accountbank}, null);
            Map<Object, String> billNos = operationResult.getBillNos();
            String number = billNos.get("0");
            return FacadeHelper.getDynamicObject("bd_finorginfo", "number", number);
        }
        return null;
    }

    // 模拟JSON解析方法（需根据实际JSON结构实现）
    private static List<Map<String, Object>> parseJsonToItems(String json) {
        // 实际开发中使用Jackson/Gson解析JSON到List<Map>或自定义对象
        return new ArrayList<>(); // 示例省略具体解析代码
    }
}
